//+------------------------------------------------------------------+
//|                                                 tradeManager.mqh |
//|                                                    Dimitri Rudel |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Dimitri Rudel"
#property link      ""

#include <basic.mqh>

extern double exExitMaxRsi = 70;
extern double exExitMinRsi = 30; 
extern double exTmgrRsi = 50;

extern double exLose = 2;

extern bool exCloseByLose = false;



void b_CloseTrades(){
   for(int i=0; i < OrdersTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if ( OrderSymbol()==Symbol()) {
            if(exCloseByLose && exitByLose()){
               OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,Red);
            }                
         }
      }
   }
}




void b_exitPositionsByType(int cmd){
   for(int i=0; i < OrdersTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

         if ( OrderSymbol()==Symbol()) {
            if(OrderType() == cmd){
               OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,Red);
            }                
         }
      }
   }
}


void tmgr_checkExit(){
   for(int i=0; i < OrdersTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

         if ( OrderSymbol()==Symbol()) {
            if(exitByRsi(OrderType())){
               OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,Red);
            }                
         }
      }
   }
}

bool exitByRsi(int opTrade){
  double rsi = iRSI(Symbol(),0,exTmgrRsi,PRICE_CLOSE,1);

  if(opTrade == OP_BUY){
      if(rsi > exExitMaxRsi){

         return (true);
      }
  }else if (opTrade ==OP_SELL){
      if(rsi < exExitMinRsi){

         return (true);
      }
  }
  return (false);
}

bool exitByLose(){
  if(OrderProfit() < (AccountEquity()* exLose / 100)*(-1)){
      return (true);
  }
  return (false);
}